<template>
  <div class="uploadSing">
    <el-upload
      v-loading="loading"
      class="avatar-uploader"
      :action="action"
      :show-file-list="false"
      :disabled="imageUrl ? true : false"
      :data="data"
      :headers="headers"
      :on-remove="handleRemoves"
      :on-error="onError"
      :on-progress="handleProgress"
      :on-success="uploadSuccess"
      :before-upload="beforeUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />

      <div v-if="imageUrl" class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreviews"
        >
          <i class="el-icon-zoom-in"></i>
        </span>

        <span
          v-if="delBtnImgFlag"
          class="el-upload-list__item-preview"
          @click="handleRemoves"
        >
          <i class="el-icon-delete"></i>
        </span>
      </div>

      <i v-else class="el-icon-plus avatar-uploader-icon"></i>

      <div class="el-upload__tip" slot="tip">{{ tips }}</div>
    </el-upload>
    
      <!-- 图片预览组件 -->
    <img-view
      :show="imageViewerVisible"
      :url-list="imageViewerList"
      @close="imageViewerVisible = false"
    >
    </img-view>
  </div>
</template>

<script>
// 引入图片预览组件
import ImgView from "@/components/imgView.vue";
export default {
  name: "fileUploadNew",
  components: {
    ImgView,
  },
  data() {
    return {
      // 上传的文件列表
      fileList: [],
        // 当前上传的文件列表
      arrayModel: [],
       // 预览的图片数据
      imageViewerList: [],
      // 是否展示图片预览组件
      imageViewerVisible: false,
      loading: false,

      dialogImageUrl: "",

      dialogVisible: false,

      imageUrl: "",

      fileData: "",

      showBtnImg: true,

      noneBtnImg: false,
    };
  },

  props: {
    value: {
      default: () => [],
    },

    ossUpload: {
      type: Boolean,

      default: false,
    },

    //提交地址,

    action: {
      type: String,

      default: "https://api.yoojet.com/Base_Manage/Upload/Filleimag",
    },

    //设置上传的请求头部

    headers: {
      type: Object,

      default: () => {},
    },

    //上传时附带的额外参数

    data: {
      type: Object,

      default: () => {},
    },

    //支持最大上传文件数

    limit: {
      type: Number,

      default: 100,
    },

    //是否选择完文件之后自动上传，默认true

    auto_upload: {
      type: Boolean,

      default: true,
    },

    disabled: {
      type: Boolean,

      default: false,
    },

    //上传之前的处理

    beforeUpload: {
      type: Function,

      default: function (file) {
        let types = ["image/jpeg", "image/jpg", "image/png"];

        const isImage = types.includes(file.type);

        if (!isImage) {
          this.$message.error("上传图片格式只能是jpg/jpeg/png!");

          return false;
        }

        if (file.size / 1024 / 1024 > 2) {
          this.$message("请控制大小在2M内");

          return false;
        }
      },
    },

    tips: {
      type: String,

      default: "只能上传jpg/png/jpeg文件，且不超过2M",
    },

    //控制删除按钮显示隐藏

    delBtnImgFlag: {
      type: Boolean,

      default: true,
    },
  },

  watch: {
    value: {
      handler(val) {
        //识别oss

        if (this.ossUpload) {
          this.imageUrl = val;
        } else {
          //多文件上传

          this.fileList = [...val] || [];
        }
      },

      deep: true,

      immediate: true,
    },
  },

  methods: {
    //放大图片
    handlePictureCardPreviews() {
        // 将展示的图片到数组
      this.imageViewerList[0] = this.imageUrl;
      // 显示预览组件
      this.imageViewerVisible = true;
    },

    //删除

    handleRemoves() {
      console.log(this.data, "this.data.type");

      this.$confirm("确定移除吗？", "提示", {
        confirmButtonText: "确定",

        cancelButtonText: "取消",

        type: "warning",
      })

        .then(() => {
          let obj = {
            url: "",

            type: this.data.type,

            side: this.data.side,

            statusDel: "delete", //添加删除标示，因为有ocr识别信息需要保留
          };

          this.$emit("fileList", obj);
        })

        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
    },

    dealImgChange(file, fileList) {
      this.noneBtnImg = fileList.length >= this.limit;
    },
   // 文件上传成功的钩子
    uploadSuccess(response, file, fileList) {

      // // 更新一下 文件列表
      this.fileList = fileList;

      // if (response.code !== 0) return;
      // 这里 arrayModel 存储的是后端返回的编译后的文件名
      this.arrayModel.push(response.Url);
      console.log('打印this.arrayModel', this.arrayModel)
      // console.log('子组件上传附件', response, file, fileList, this.arrayModel)
      let fileData = fileList.map((item) => {
        console.log('upload组件文件上传', fileList, item, response)
        return {
          name: item.name,
          url: item.response?item.response.Data:item.Data,
        };
      });
      let newFileData = [];
      fileData.forEach((item) => {
        newFileData.push(item.url);
      });
      console.log('上传后的upload子组件里的',fileData , newFileData)
      // console.log('需要传递的', newFileData)
      // 上传成功则往v-model数据上添加
      this.$emit("uploadSuccess", fileData, newFileData);
      this.loading=false
      // 赋值选中好的图片  后续有只上传一张图片的条件下使用
      this.imageUrl= newFileData[0]
    },
    // 删除文件是触发的钩子
    handleRemove(file) {
      console.log("子组件删除附件", file, this.fileList);
      // 看当前有多少个文件
      for (let i = 0; i < this.fileList.length; i++) {
        // 要删除的文件 == 已经上传过的文件
        if (file.uid == this.fileList[i].uid) {
          // 从文件列表中删除
          this.fileList.splice(i, 1);
          this.arrayModel.splice(i, 1);

          let fileData = this.fileList.map((item) => {
            return {
              name: item.name,
              url: item.response?item.response.url:item.url,
            };
          });

          let newFileData = [];
          fileData.forEach((item) => {
            newFileData.push(item.url);
          });

          this.$emit("handleRemove", fileData, newFileData);

          // 后续打开
          // 发起请求 删除文件
          // this.$http({
          //   url: this.$http.adornUrl(`/sys/file/deleteRelated`),
          //   method: "post",
          //   params: fileName: this.arrayModel[i]
          // }).then(res=>{
          //   // 更新绑定的v-model
          //   this.arrayModel.splice(i, 1);
          //   this.$emit("update", this.arrayModel);
          // });
        }
      }
    },
    // 文件上传时
    handleProgress() {
      this.loading = true;
    },

    onError(res) {
      this.loading = false;
    },

    uploadFile(file) {
      this.fileData.append("file", file.file);
    },
  },
};
</script>

<style lang="less">

.uploadSing{
    /*默认上传区域样式*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  /*上传区域鼠标hover样式*/
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  /*默认上传区域样式*/
  .avatar-uploader-icon,.el-upload--picture-card {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height:150px;
    line-height: 150px;
    text-align: center;
  }
    /*上传后的图片样式*/
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }

  .el-upload-list--picture-card .el-upload-list__item {
      width: 150px;
      height: 150px;
  }

  .el-upload__tip {

    text-align: center;

  }



  .uoloadSty .el-upload--picture-card{
    border:1px solid red;

    font-size: 28px;

    color: #8c939d;

    width: 80px;

    height: 80px;

    line-height: 80px;

    text-align: center;

  }

  .disUoloadSty .el-upload--picture-card{

    display: none;   /* 上传按钮隐藏 */

  }
 /* 上传后的图片的遮罩层hover样式 */
  .el-upload:hover .el-upload-list__item-actions {
    visibility: visible;
    transition: 1s;
    z-index: 200;
    width: 150px;
    height:150px;
  }
   /* 上传后的图片的遮罩层默认样式 */
  .el-upload-list__item-actions {
    width: 150px;
    height: 150px;
    position: absolute;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
    visibility: hidden;
    background: rgba(0, 0, 0, 0.4);
  }

  .el-upload-list__item-preview {

    display: inline-block;

    width: 20px;

    height: 20px;

    display: flex;

    align-items: center;

    justify-content: center;

  }

  .el-icon-zoom-in:before,

  .el-icon-delete:before {

    font-size: 30px;

    color: #fff;

  }
 



}
</style>
